package asia.kalin;

import asia.kalin.utils.PromptUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class ExecutePython {
    public static void main(String[] args) {
        try {
            // 1. 定义命令及参数
            ProcessBuilder pb = new ProcessBuilder(
                    "python", // 或 "python3"，根据环境调整
                    "janus.py",
                    PromptUtil.prompt,
                    "https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png"
            );

            // 可选：设置工作目录（如脚本不在当前目录）
            // pb.directory(new File("/path/to/script/directory"));
            pb.environment().put("PYTHONIOENCODING", "utf-8");

            // 2. 启动进程
            Process process = pb.start();

            // 3. 读取标准输出流
            InputStream inputStream = process.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String line;
            System.out.println("Python脚本输出:");
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 4. 读取错误流
            InputStream errorStream = process.getErrorStream();
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorStream));
            System.err.println("错误信息:");
            while ((line = errorReader.readLine()) != null) {
                System.err.println(line);
            }

            // 5. 等待进程结束并获取退出码
            int exitCode = process.waitFor();
            System.out.println("退出码: " + exitCode);

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}